const express = require('express')
const userRouter = require('../router/user.js')
const app = express()
const models = require('../db/models')//模型对象
//先进入all进行校验参数通过后进入其他路由
app.all('*', validateNameMiddleWare)

function loginMiddleWare (req, res, next) {
	console.log('登录请求来啦')
	next()
}
//加载应用级别中间件
app.use(loginMiddleWare)
//加载内置中间件
app.use(express.static('static', {
	//设置默认扩展名   通过http://localhost:3000/static找到static.html
	extensions: ['html', 'htm']
}))
//加载路由
//app.use(userRouter)//http://localhost:3000/userdemo?name=123
app.use('/user', userRouter)//http://localhost:3000/user/userdemo?name=123

//中间件完整结构
//1.一个函数 2. err, req, res, next --> function

//中间件作用
//1.异常处理
//2.处理业务功能然后转交控制权--next
//3.响应请求--结束响应-->作为路由的处理函数
function validateNameMiddleWare ( req, res, next) {
	//设置响应头解决跨域
	res.header('Access-Control-Allow-Origin', '*');
	res.header('Access-Control-Allow-Headers', 'authorization, Content-Type, Content-Length, Authorization, Accept, X-Requested-With');
	res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
	//没有name参数或者参数为空值时的异常处理
	/* let { name } = req.query
	console.log(req.query)
	if(JSON.stringify(req.query) === '{}' || name === '0' || name === 'undefined' || name === 'null' || name === ''){
		res.json({
			message: '缺少name参数'
		})
	}else{
		next()
	} */
	//不做参数校验时直接放过
	next()
}

//ES7 async await写法
//创建一条数据
app.get('/create', async (req, res)=>{
	let { name } = req.query//get查询地址'?'后面的参数
	let result = await models.userlist.create({
		name,
		age: 123456,
		lastName: '111',
		firstName: 'zqf',
	})
	res.json({result,message: '创建成功'})
})
//查询所有数据
app.get('/list', async (req, res, next)=>{
	let result = await models.userlist.findAll()
	console.log('查询列表成功')
	res.json({result,message: '查询列表成功'})
})
//查询其中一条数据，restful风格携带参数
app.get('/detail/:id', async (req, res, next)=>{
	let {id} = req.params//查询接口地址'?'前面的参数
	let result = await models.userlist.findOne({
		where:{ id }
	})
	res.json({result,message: '查询详情成功'})
})

let server = app.listen(3000, () => {
	console.log(`server is started on localhost : 3000 by zhangqianfeng`)
})